package cn.edu.scau.disk.controller;

import cn.edu.scau.disk.exception.CommonException;
import cn.edu.scau.disk.service.UserService;
import cn.edu.scau.disk.utils.R;
import cn.edu.scau.disk.utils.RedisConstant;
import cn.edu.scau.disk.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Validated
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;

    @PostMapping("login")
    public R login(String username,String password) throws CommonException {
        String token=userService.login(username,password);
        return R.ok().put("token",token);
    }


    @PostMapping("register")
    public R register(String username,String password,String confirmPwd) throws CommonException {
        userService.register(username,password,confirmPwd);
        return R.ok();
    }

    @PostMapping("logout")
    public R logout(@RequestHeader("token") String token){
        userService.logout(token);
        return R.ok();
    }

    @PutMapping
    public R resetPass(@RequestHeader("token") String token,String confirmPwd,String oldPwd,String newPwd) throws CommonException {
        Integer userId = Integer.valueOf(redisUtil.get(RedisConstant.TOKEN+token));
        userService.resetPwd(userId,oldPwd,newPwd,confirmPwd);
        return R.ok();
    }
}
